package com.yisu.expressway.onedollar.fragment;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.reflect.TypeToken;
import com.yisu.expressway.R;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.activity.DetailActivity;
import com.yisu.expressway.onedollar.activity.OneDollarMainActivity;
import com.yisu.expressway.onedollar.activity.OrderShowDetailActivity;
import com.yisu.expressway.onedollar.adapter.PicGridListAdapter;
import com.yisu.expressway.onedollar.model.OrderShowItem;
import com.yisu.expressway.onedollar.widget.NoScrollGridView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Kaven on 2016/12/19.
 */

public class OrderShowFragment extends BasicFragment implements
        PagingRecyclerView.SampleActionListener, PicGridListAdapter.PicItemClickListener {
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mRecyclerView;

    @Bind(R.id.empty)
    protected View emptyView;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty_iv)
    protected ImageView mEmptyIv;

    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;

    @OnClick(R.id.empty_action)
    public void onClick(View view) {
        if (TAG_ACTION_NET_ERR.equals(view.getTag())){
            mRecyclerView.refreshData();
        }else if (TAG_ACTION_NORMAL.equals(view.getTag())){
            startTargetActivity(OneDollarMainActivity.class);
        }
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.fragment_order_show;
    }

    @Override
    protected void initPresenter() {

    }

    @Override
    protected void releasePresenter() {

    }

    @Override
    protected void getIntentData(Intent intent) {

    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews(View view) {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(getContext(),
                LinearLayoutManager.VERTICAL);
        mRecyclerView.init(mListDivider, new LinearLayoutManager(getContext()), this, 20);
    }

    @Override
    protected void bindEvents() {

    }

    private View createHeaderView() {
        View headerView = getActivity().getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mRecyclerView.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    @Override
    public void fetchData(int start, int pageSize) {
        if (pageSize <= 0) {
            return;
        }
        Map<String, Object> params = new HashMap();

        int pageIndex = getPageIndex(start, pageSize);

        params.put("pageindex", pageIndex);
        params.put("pagesize", pageSize);
        ApiClientHelper.postApi(ApiSetting.getMyOrderShowInfo(),
                new TypeToken<List<OrderShowItem>>() {
                }, new JSONObject(params), new Response.Listener<ApiResult<List<OrderShowItem>>>() {
                    @Override
                    public void onResponse(ApiResult<List<OrderShowItem>> result) {
                        if (!result.success) {
                            mRecyclerView.dataFetchFail(result.getMsg());
                            showEmptyView(true, true);
                            return;
                        }
                        List<OrderShowItem> result1 = result.getResult();
                        if (result1 == null || result1.isEmpty()){
                            showEmptyView(true, false);
                        }else {
                            mRecyclerView.dataFetchDone(result1);
                        }

                        if (mAnimation != null) {
                            mRefreshLayout.setRefreshing(false);
                            mAnimation.stop();
                            carImage.setImageResource(R.color.colorTransparent);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        mRecyclerView.dataFetchFail(volleyError.getMessage());
                        showEmptyView(true, true);
                    }
                }, this);
    }

    private int getPageIndex(int start, int pageSize) {
        int round = start / pageSize;

        return round + 1;
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.my_ordershow_item_list,
                null);
        return new OrderShowViewHolder(itemView);
    }
    public static final String TAG_ACTION_NET_ERR = "tag_action_net_err";
    public static final String TAG_ACTION_NORMAL = "tag_action_normal";
    protected void showEmptyView(boolean showEmpty, boolean netError) {
        emptyView.setVisibility(showEmpty ? View.VISIBLE : View.GONE);
        mRefreshLayout.setVisibility(showEmpty ? View.GONE : View.VISIBLE);
        if (showEmpty){

            if (netError) {
                mEmptyActionTv.setText(getString(R.string.one_dollar_empty_action_retry));
                mEmptyActionTv.setTag(TAG_ACTION_NET_ERR);
                mEmptyDesTv.setText(getString(R.string.one_dollar_empty_net_error));
                mEmptyIv.setImageDrawable(getResources().getDrawable(R.drawable.ic_no_signal));
            }else {
                mEmptyActionTv.setTag(TAG_ACTION_NORMAL);
	            mEmptyActionTv.setVisibility(View.GONE);
                mEmptyDesTv.setText(getString(R.string.one_dollar_empty_ordershow));
                mEmptyIv.setImageDrawable(getResources().getDrawable(R.drawable.ic_no_ordershow));
            }
        }

    }
    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final OrderShowViewHolder holder = (OrderShowViewHolder) _holder;
        final OrderShowItem item = (OrderShowItem) _item;
        String goodspic = item.goodsPic;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getActivity()).load(picShow).asBitmap()
                        .placeholder(R.drawable.pic_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(holder.mCoverIv);
            }
        } else {
            holder.mCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.pic_loading));
        }
        holder.mGoodNameTv.setText(item.goodsName);
        holder.mTimeTv.setText(item.createTime);
        holder.mContentTv.setText(item.evaluateContent);
        String evaluatepic = item.evaluatePic;
        if (!TextUtils.isEmpty(evaluatepic)) {
            String[] split = evaluatepic.split(",");
            if (split.length > 0) {
                List<String> strings = Arrays.asList(split);
                PicGridListAdapter picGridListAdapter = new PicGridListAdapter(getContext(),
                        strings, this);
                holder.mPicGridView.setAdapter(picGridListAdapter);
                picGridListAdapter.notifyDataSetChanged();
            }
        }

        holder.mRootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jump2OrderShowDetailPage(item.recordId);
            }
        });
    }

    public void jump2OrderShowDetailPage(long recordId) {
        if (recordId <= 0) {
            return;
        }
        OrderShowDetailActivity.launch(getActivity(), recordId);
    }

    @Override
    public void onPicItemClick(String picUrl) {
        if (TextUtils.isEmpty(picUrl)) {
            return;
        }
        jump2OriginalPicPage(picUrl);
    }

    public void jump2OriginalPicPage(String picUrl) {
        if (TextUtils.isEmpty(picUrl)) {
            return;
        }
        DetailActivity.launch(getActivity(), picUrl, DetailActivity.TYPE_URL, "");
    }

    class OrderShowViewHolder extends BaseRvAdapter.SampleViewHolder {
        @Bind(R.id.rootView)
        View mRootView;
        @Bind(R.id.iv_cover)
        ImageView mCoverIv;
        @Bind(R.id.tv_winner)
        TextView mGoodNameTv;
        @Bind(R.id.tv_time)
        TextView mTimeTv;
        @Bind(R.id.tv_evaluatecontent)
        TextView mContentTv;
        @Bind(R.id.gridview)
        NoScrollGridView mPicGridView;

        public OrderShowViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
